package org.callisto;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DbLib {
	
	private static Connection conn;
	public static void executeUpdate(String sql) throws Exception {
		conn = getDatabaseConnection();
		Statement s = conn.createStatement();
        s.executeUpdate(sql);
	}
	
	public static ResultSet query(String sql) throws Exception {
		conn = getDatabaseConnection();
		Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
		ResultSet srs = stmt.executeQuery(sql);
		return srs;
	}
            
	public static Connection createConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		try {
			String userName = "root"; // TODO: Extract connection parameters. Encrypt passwords with httpasswd.
	        String password = "root";
	        String url = "jdbc:mysql://127.0.0.1:3306/klavier";
	        Class.forName ("com.mysql.jdbc.Driver").newInstance ();
	        conn = DriverManager.getConnection (url, userName, password);
	        System.out.println ("Database connection established");
		} catch (Exception e) {
            e.printStackTrace();
        }
		return conn;
	}
	
	public static void tearDown() {
        if (conn != null) {
            try {
                conn.close ();
                System.out.println ("Database connection terminated");
            } catch (Exception e) { /* ignore close errors */ }
        }
	}
	
	public static Connection getDatabaseConnection() throws Exception {
		//while (retryCount++ < RETRY_LIMIT) {
			//System.out.println("Attempt #" + retryCount + " for database connection");
			try {
				if (conn == null || conn.isClosed()) {
					conn = createConnection();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		//}
		//if (retryCount == RETRY_LIMIT ) {
		//	throw new Exception("Retry limit exceeded");
		//}
		return conn;
	}
}
